package dao

import (
	"errors"
	"time"
	"user_srv/model"
	"user_srv/user"
)

// 信任设备添加
func CreateTrustedDevices(in *user.CreateTrustedDevicesRequest) (*model.TrustedDevices, error) {
	lastTime, err := time.Parse(time.DateTime, in.LastTime)
	if err != nil {
		return nil, errors.New("时间格式不正确")
	}
	devices := model.TrustedDevices{
		UserId:     uint(in.UserId),
		DeviceHash: in.DeviceHash,
		DeviceName: in.DeviceName,
		DeviceType: uint(in.DeviceType),
		System:     uint(in.System),
		LastIp:     in.LastIp,
		LastTime:   lastTime,
		Status:     uint(in.Status),
	}
	if err := devices.CreateTrustedDevices(); err != nil {
		return nil, errors.New("信任设备添加失败")
	}
	return &devices, err
}

// 信任设备修改
func UpdateTrustedDevices(in *user.UpdateTrustedDevicesRequest) (*model.TrustedDevices, error) {
	var device model.TrustedDevices
	if err := device.GetTrustedDevicesById(int(in.Id)); err != nil {
		return nil, err
	}
	if device.Status != 1 {
		return nil, errors.New("该设备已无效，禁止修改")
	}
	lastTime, err := time.Parse(time.DateTime, in.LastTime)
	if err != nil {
		return nil, errors.New("时间格式不正确")
	}
	device.DeviceHash = in.DeviceHash
	device.DeviceName = in.DeviceName
	device.DeviceType = uint(in.DeviceType)
	device.System = uint(in.System)
	device.LastIp = in.LastIp
	device.LastTime = lastTime
	device.Status = uint(in.Status)
	err = device.UpdateTrustedDevices(int(in.Id))
	if err != nil {
		return nil, errors.New("信任设备修改失败")
	}
	return &device, err
}

// 信任设备删除
func DeleteTrustedDevices(in *user.DeleteTrustedDevicesRequest) (*model.TrustedDevices, error) {
	var device model.TrustedDevices
	if err := device.GetTrustedDevicesById(int(in.Id)); err != nil {
		return nil, err
	}
	err := device.DeleteTrustedDevices(int(in.Id))
	if err != nil {
		return nil, errors.New("信任设备删除失败")
	}
	return &device, err
}

// 信任设备列表
func GetTrustedDevicesList(in *user.GetTrustedDevicesListRequest) ([]*user.TrustedDevicesList, error) {
	var devices model.TrustedDevices
	list, err := devices.GetTrustedDevicesList()
	if err != nil {
		return nil, errors.New("信任列表展示失败")
	}
	var TrustedDevice []*user.TrustedDevicesList
	for _, dev := range list {
		lists := user.TrustedDevicesList{
			Id:         int64(dev.Id),
			DeviceHash: dev.DeviceHash,
			DeviceName: dev.DeviceName,
			DeviceType: int64(dev.DeviceType),
			System:     int64(dev.System),
			LastIp:     dev.LastIp,
			LastTime:   dev.LastTime.Format("2006-01-02 15:04:05"),
			Status:     int64(dev.Status),
		}
		TrustedDevice = append(TrustedDevice, &lists)
	}
	return TrustedDevice, err
}
